angular.module('ionicApp.diary', [])

.controller('diaryCtrl', function($scope, $ionicModal, $ionicSideMenuDelegate, $ionicActionSheet, $ionicPopup, diaryService, $timeout) {
    // 创建并载入模型
    $ionicModal.fromTemplateUrl('templates/diary/add_diary.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.newOneModal = modal;
    });

    $ionicModal.fromTemplateUrl('templates/diary/show_diary.html', {
        scope: $scope
    }).then(function(modal) {
        $scope.showDetailModal = modal;
    });

    $scope.method = {
        init: function() {
            $scope.activeIndex = diaryService.getIndex();
            $scope.cateID = diaryService.getCateID();
            $scope.activeCate = $scope.cateID[$scope.activeIndex];
            $scope.activeList = diaryService.getDiarys($scope.activeCate);
            $scope.newModel = {
                op: "",
                cate: "",
                title: "",
                text: "",
                image: "",
                time: ""
            };
            $scope.detail = {
                cate: "",
                title: "",
                text: "",
                image: "",
                time: ""
            };
        },
        slide: function(direction) {
            direction === 'left' ? $ionicSideMenuDelegate.toggleLeft() : $ionicSideMenuDelegate.toggleRight();
        },
        modalCtrl: function(ctn, op, callback) {
            var modalCtn = {
                "newOne": $scope.newOneModal,
                "showDetail": $scope.showDetailModal
            };
            // 传入多个modal，执行统一操作, op === 'hide' || op === 'show'
            if (angular.isArray(ctn)) {
                op === "hide" ? ctn.forEach(function(item, index) {
                    modalCtn[item].hide();
                }) : ctn.forEach(function(item, index) {
                    modalCtn[item].show();
                });
                return false;
            }

            op === "hide" ? modalCtn[ctn].hide() : modalCtn[ctn].show();
            callback && callback.call(null);
        },
        addCate: function(callback) {
            var that = this,
                prompt = $ionicPopup.show({
                    template: '<input type="text" ng-model="newTitle" placeholder="new category">',
                    title: "新建分类名",
                    scope: $scope,
                    buttons: [{
                        text: "cancel"
                    }, {
                        text: "save",
                        type: "button-positive",
                        onTap: function(e) {
                            if (!this.scope.newTitle) {
                                $ionicPopup.alert({
                                    title: "分类名不能为空"
                                });
                                e.preventDefault();
                            } else {
                                return this.scope.newTitle;
                            };
                        }
                    }]
                });

            prompt.then(function(res) {
                if (!res) return false;

                if (!diaryService.addCateID(res)) {
                    $ionicPopup.alert({
                        title: "已存在相同分类"
                    });
                    return false;
                }

                diaryService.addCateID(res);
                diaryService.setIndex($scope.cateID.length);

                that.init();
                callback && callback.call(null);
            });
        },
        delCate: function(cate, index) {
            var that = this,
                actionSheet = $ionicActionSheet.show({
                    buttons: [{
                        text: "Edit CateID",
                        // custom event
                        action: function() {
                            var prompt = $ionicPopup.show({
                                template: '<input type="text" ng-model="newTitle" placeholder="edit cateID">',
                                title: "修改分类名",
                                scope: $scope,
                                buttons: [{
                                    text: "cancel"
                                }, {
                                    text: "save",
                                    type: "button-positive",
                                    onTap: function(e) {
                                        if (!this.scope.newTitle) {
                                            $ionicPopup.alert({
                                                title: "分类名不能为空"
                                            });
                                            e.preventDefault();
                                        } else {
                                            return this.scope.newTitle;
                                        };
                                    }
                                }]
                            });
                            prompt.then(function(res) {
                                diaryService.editCateID(cate, res);
                                that.init();
                            });
                        }
                    }],
                    destructiveText: 'Delete',
                    destructiveButtonClicked: function() {
                        diaryService.delCateID(cate);
                        that.init();
                        // Return true to close the action sheet, or false to keep it opened.
                        return true;
                    },
                    titleText: "modify your List",
                    cancelText: "Cancel",
                    cancel: function() {
                        return true;
                    },
                    // Called when one of the non-destructive buttons is clicked, with the index of the button that was clicked and the button object.
                    buttonClicked: function(index) {
                        var fn = this.buttons[index].action;
                        fn && fn.call(null);
                        return true;
                    }
                });
            // 延时不操作
            try {
                $timeout(function() {
                    actionSheet();
                }, 4000);
            } catch (e) {
                return true;
            }

        },
        showDiarys: function(index) {
            diaryService.setIndex(index);
            this.init();
            $ionicSideMenuDelegate.toggleLeft(false);
        },
        addDiary: function(obj) {
            var that = this;
            if (!$scope.activeCate) {
                $ionicPopup.alert({
                    title: "请新建分类，再创建日志，谢谢~"
                }).then(function(res) {
                    that.addCate();
                    return false;
                });
            }

            if (obj.op === "edit") {
                diaryService.editDiary($scope.detail, obj);
            } else {
                var time = new Date();
                diaryService.addDiary({
                    cate: $scope.activeCate,
                    title: obj.title,
                    text: obj.text,
                    image: obj.image,
                    time: time.toGMTString().substring(5, 25)
                });
            }

            that.init();
            that.modalCtrl("newOne", "hide");
        },
        delDiary: function(obj) {
            var that = this;
            $ionicPopup.confirm({
                title: "确认删除这条日志吗？"
            }).then(function(res) {
                if (res) {
                    diaryService.delDiary({
                        cate: obj.cate,
                        title: obj.title,
                        time: obj.time
                    });
                    that.init();
                }
            });
        },
        delDiarys: function() {
            var that = this;
            $ionicPopup.confirm({
                title: "确认要将所有数据清空吗？此操作不可逆！"
            }).then(function(res) {
                if (res) {
                    diaryService.delAllData();
                }
                that.init();
            });
        },
        showDiary: function(obj) {
            $scope.detail = {
                cate: obj.cate,
                title: obj.title,
                text: obj.text,
                image: obj.image,
                time: obj.time
            };
            this.modalCtrl("showDetail", "show");
        },
        editDiary: function(obj) {
            this.modalCtrl("showDetail", "hide");
            $scope.newModel = {
                op: "edit",
                cate: obj.cate,
                title: obj.title,
                text: obj.text,
                image: obj.image,
                time: obj.time
            };
            this.modalCtrl("newOne", "show");
        }
    }

    $scope.method.init();
});
